<template>
  <div>
    <a-form :form="form">
      <a-form-item>
        <a-input
          placeholder="账号"
          autocomplete="off"
          v-decorator="[
            'account',
            {
              rules: [{ required: true, message: '用户名不能为空!' }]
            }
          ]"
        >
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input
          type="password"
          placeholder="密码"
          autocomplete="off"
          ref="password"
          v-decorator="[
            'password',
            {
              rules: [{ validator: validatePassword }]
            }
          ]"
        >
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-row :gutter="24">
          <a-col :span="14">
            <a-input
              placeholder="验证码"
              :maxLength="4"
              @keydown.enter.native="handleSubmit"
              autocomplete="off"
              v-decorator="['verifyCode', { rules: [{ required: true, validator: validateCode }] }]"
            >
            </a-input>
          </a-col>
          <a-col :span="10" style="text-align: right">
            <img
              class="codeImg"
              :src="imgSrc"
              style="height: 32px; width: 100%; position: relative; top: -2px"
              @click="refreshCode"
              v-if="imgSrc"
            />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item style="margin: 44px 0 12px">
        <a-button type="primary" :loading="loginBtn" class="login-btn" @click="handleSubmit">登录</a-button>
      </a-form-item>
    </a-form>

    <multi-tenant-modal ref="MultiTenantModal" @ok="TenantModalOk" @error="TenantModalError"></multi-tenant-modal>
  </div>
</template>

<script>
import { validateCode, validatePassword } from '@/utils/validate'
import { getVerifyCode } from '@/api/user'
import MultiTenantModal from './MultiTenantModal'

export default {
  name: 'LoginForm',
  components: { MultiTenantModal },
  data () {
    return {
      timeGo: false,
      time: 60,
      loginBtn: false,
      imgSrc: '',
      model: {},
      tenantNo: '',
      form: this.$form.createForm(this)
    }
  },
  watch: {
    'model.account' (val) {
      if (val) {
        this.model.tenantNo = ''
      }
    }
  },
  beforeCreate () {
    // this.form = this.$form.createForm(this)
  },

  mounted () {
    this.refreshCode()
  },

  destroyed () {
    clearInterval(this.timer)
  },

  methods: {
    refreshCode () {
      getVerifyCode().then(res => {
        let url = window.URL.createObjectURL(res)
        this.imgSrc = url
      })
    },

    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          // if (this.isLocking(values.account)) {
          //   // 用户已被锁定
          //   return
          // }
          this.model = Object.assign({}, this.model, values)
          values.randomStr = this.randomStr
          this.loginBtn = true
          this.$nextTick(() => {
            if (this.model.tenantNo) {
              this.login(this.model)
            } else {
              this.$refs.MultiTenantModal.edit(values.account)
            }
          })
        }
      })
    },

    TenantModalOk (data) {
      this.model.tenantNo = data.tenantNo
      this.model.userNo = data.userNo
      this.login(this.model)
    },
    TenantModalError () {
      this.loginBtn = false
      this.refreshCode()
    },

    // 用户登录
    login (data) {
      this.$store
        .dispatch('Login', data)
        .then(res => {
          this.loginBtn = false
          if (res.code === 0) {
            this.$notification.success({
              message: '系统提示',
              description: res.msg,
              duration: 3,
              top: '62px'
            })
            this.unLockingUser(data.account)
            this.$router.push({ path: '/' })
            this.model.tenantNo = ''
          } else if (res.code === 210000) {
            this.$message.warning(res.msg)
            this.$emit('stepChange', 3, this.model)
          } else {
            this.$message.warning(res.msg)
          }
        })
        .catch(() => {
          // this.refreshCode()
          this.loginBtn = false
          this.lockingUser(data.account)
          // this.form.setFieldsValue({ verifyCode: '' })
        })
        .finally(() => {
          this.form.setFieldsValue({ verifyCode: '' })
          this.refreshCode()
        })
    },
    // 验证用户是否被锁定
    isLocking (name) {
      const locking = this.$ls.get('User_Locking')
      if (locking[name] && locking[name]['num'] >= 5) {
        if (locking[name].expire - Date.now() > 0) {
          // 处于锁定时间中
          this.$message.error(
            `用户已经被锁定，请于${Math.ceil((locking[name].expire - Date.now()) / (60 * 1000))}分钟之后再试`
          )
          return true
        } else {
          this.unLockingUser(name)
          return false
        }
      } else {
        return false
      }
    },

    // 锁定用户
    lockingUser (name) {
      const locking = this.$ls.get('User_Locking')

      let userLocking = locking[name]

      if (userLocking) {
        if (userLocking.num === 4) {
          userLocking.num += 1
          userLocking.expire = Date.now() + 10 * 60 * 1000 // 锁定时间为10分钟
        } else {
          userLocking.num += 1
        }
      } else {
        locking[name] = { num: 1 }
      }

      this.$ls.set('User_Locking', locking)
    },

    // 解锁用户
    unLockingUser (name) {
      const locking = this.$ls.get('User_Locking')
      if (locking[name]) {
        delete locking[name]
      }
      this.$ls.set('User_Locking', locking)
    },

    validatePassword,
    validateCode
  }
}
</script>

<style lang="less" scoped>
.login-btn {
  width: 100%;
  font-size: 14px;
}
</style>
